﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Microsoft.Maps.MapControl;
using System.Windows.Printing;

namespace SMIL.Client.Print
{
    public partial class PrintWindow : ChildWindow
    {
        const string _APPKEY = "SMIL.BingMap.CredentialsKey";
        const string _SPSITEURL = "SPWEB";
        PrintDocument pd;

        public PrintWindow(Location center,double zoom)
        {
            InitializeComponent();
            Loaded += PrintWindow_Loaded;

           
            map.CredentialsProvider = 
                new ApplicationIdCredentialsProvider((Application.Current.Resources.Contains(_APPKEY)) ? Application.Current.Resources[_APPKEY] as string : "");
            map.Height = 585;
            map.Width = 780;
            map.Center = center;
            map.ZoomLevel = zoom;
            printDate.Text = DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
            pd = new PrintDocument();
            
            pd.PrintPage += new EventHandler<PrintPageEventArgs>(pd_PrintPage);
        }
        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.PageVisual = Ready2Print;
        }
        void PrintWindow_Loaded(object sender, RoutedEventArgs e)
        {
            map.IsEnabled = false;

            if (ParentMap.Mode is RoadMode)
                map.Mode = new RoadMode();
            else if (ParentMap.Mode is AerialMode)
                if (((AerialMode)ParentMap.Mode).Labels)
                    map.Mode = new AerialMode(true);
                else
                    map.Mode = new AerialMode(false);

            CopyMapChilds(map, ParentMap, true);
        }

        public Map ParentMap{get; set;}

        void OKButton_Click(object sender, RoutedEventArgs e)
        {
            
            pd.Print("Print from SMIL");
            pd.EndPrint += new EventHandler<EndPrintEventArgs>(pd_EndPrint);
           
        }

        void pd_EndPrint(object sender, EndPrintEventArgs e)
        {
            this.DialogResult = true;
            CopyMapChilds(ParentMap, map, false);
        }

        private void CopyMapChilds(Map destMap, Map sourceMap, bool order)
        {
            for (int i = sourceMap.Children.Count - 1; i >= 0; i--)
            {
                UIElement uiElm = sourceMap.Children[i];
                sourceMap.Children.Remove(uiElm);
                destMap.Children.Insert(0, uiElm);
            }
        }

        void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            CopyMapChilds(ParentMap, map, false);
        }

    }
}